<template>
  <a-modal ref="dialogImportRef" :open="dialogVisible" title="导入流程数据(同时支持xml/json)" @cancel="handleClose()" width="60%">
    <div style="padding: 0px 5px; height: 450px; overflow-y: scroll">
      <a-textarea v-model:value="graphJsonStr" placeholder="" :rows="20" />
    </div>
    <template #footer>
      <a-button @click="handleClose">取 消</a-button>
      <a-button type="primary" @click="handleSubmit">确 定</a-button>
      <a-dropdown placement="top" trigger="click" style="float: left" v-if="localStorageLfData.length">
        <a-button link type="primary" @click.prevent>
          选择
          <!-- <Icon icon="ant-design:setting-outlined" /> -->
          <a-icon icon="ant-design:delete-outlined" />
        </a-button>
        <template #overlay>
          <a-menu @click="handleCommand">
            <a-menu-item :key="item.value" v-for="item in localStorageLfData">
              {{ item.label }}&nbsp;&nbsp;
              <a-icon icon="ant-design:arrow-down-outlined" @click="handleRemove(item.value)" />
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, defineExpose, computed, unref, defineEmits } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  const dialogVisible = ref(false);
  const graphJsonStr = ref('');
  // 定义外部事件
  const emits = defineEmits(['on-submit']);
  // 显示，由父组件调用
  const show = () => {
    dialogVisible.value = true;
  };
  const refreshFlag = ref(1);
  // 本地保存数据
  const localStorageLfData = computed<Array<any>>(() => {
    const res: any = [];
    if (refreshFlag.value > 0) {
      Object.keys(window.localStorage).forEach((key) => {
        if (key.startsWith('LFDATA###')) {
          const arr = key.split('###');
          res.push({
            value: key,
            label: arr[2],
          });
        }
      });
    }
    return res;
  });
  // 处理确定按钮事件
  const handleSubmit = () => {
    if (unref(graphJsonStr)) {
      emits('on-submit', unref(graphJsonStr));
      dialogVisible.value = false;
    } else {
      createMessage.error('导入数据不能为空');
    }
  };
  // 处理导入选项选中事件
  const handleCommand = (key: string) => {
    graphJsonStr.value = window.localStorage.getItem(key) || '';
  };
  // 处理删除事件
  const handleRemove = (key: string) => {
    window.localStorage.removeItem(key);
    refreshFlag.value++;
  };
  const handleClose = () => {
    dialogVisible.value = false;
    graphJsonStr.value = '';
  };
  /**
   * 刷新
   */
  const refresh = () => {
    refreshFlag.value++;
  };
  defineExpose({
    show,
    refresh,
  });
</script>
